package tr.edu.ege.communicator;

import java.io.ObjectInputStream;
import java.net.Socket;

import tr.edu.ege.communicator.util.CommunicatorLogger;

/**
 * This class invokes as a thread when new connection request is made to the
 * peer.
 * 
 * @author Onur ULUSU
 * 
 */
public class PeerThread extends Thread {

	/**
	 * Socket of the current connection.
	 */
	private Socket socket;

	/**
	 * Message which came from sender.
	 */
	private Message message;

	/**
	 * Peer instance which owns this connection.
	 */
	private Peer peer;

	/**
	 * Creates a new PeerThread instance.
	 * 
	 * @param socket
	 * @param peer
	 */
	public PeerThread(Socket socket, Peer peer) {
		super();
		this.socket = socket;
		this.peer = peer;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		super.run();

		ObjectInputStream ois = null;
		try {
			// getting inputstram of the socket and creating an object o.s.
			ois = new ObjectInputStream(socket.getInputStream());
			// reading the serialized message..
			message = (Message) ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		CommunicatorLogger.log("Received message :\n" + message.toString());

		// add new message to the queue and notify all listeners..
		peer.getQueue().addMessageToQueue(message);
		peer.notifyAllListeners();
	}
}
